package Servlet;

import DAO.*;
import POJO.Response;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

import Util.JWTUtils;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.gson.Gson;
//https://blog.csdn.net/qq_43842093/article/details/121276552
//https://zhuanlan.zhihu.com/p/451745696
public class Signup extends HttpServlet{
    @Override
    public void init() throws ServletException {
        super.init();
    }
    class SignUpData {
        private int userId;
        private String userToken;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);
        UserDAO userDao = new UserDAO();
        String regUsername = req.getParameter("username");
        String regPassword = req.getParameter("password");

        //System.out.println();
        resp.setContentType("text/json;charset=UtF-8");
        PrintWriter out = resp.getWriter();
        Response res;
        try{
            if(userDao.userNameExisted(regUsername)){
                res = new Response(1000,"用户名已存在",null);
            }else {
                int userId = userDao.reg(regUsername, regPassword);
                SignUpData tempdata = new SignUpData();
                tempdata.userId = userId;
                HashMap<String, Integer> user_info = new HashMap<String, Integer>();
                user_info.put("userId", userId);
                tempdata.userToken = JWTUtils.getToken(user_info);
                res = new Response(0,"注册成功",tempdata);

            }
        }catch(SQLException e){
            System.out.println(e);
            res = new Response(1001,"用户名或密码不正确",null);
        }
        Gson gson = new Gson();
        String json = gson.toJson(res);

        out.println(json);
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
